<template>
  <div>
    <div class="taskCreate" v-if="showCreate">
      <van-form>
        <!-- <van-field
          v-model="show.beginTime_plan"
          label="开始时间"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true, message: '请确定计划时间' }]"
          readonly
          @click="onclickBeginTimePlan"
        />-->
        <van-field
          v-if="taskInfo.state !== 5"
          v-model="taskInfo.taskName"
          type="text"
          autosize
          label="巡道名称"
        />
        <van-field
          v-if="taskInfo.state !== 5"
          v-model="show.beginTime_plan"
          label="开始时间"
          placeholder="请选择"
          input-align="right"
          readonly
          :rules="[{ required: true, message: '请选择相关信息' }]"
          @click="onclickBeginTimePlan"
        />
        <van-field
          v-if="taskInfo.state !== 5"
          v-model="show.endTime_plan"
          label="结束时间"
          placeholder="请选择"
          input-align="right"
          readonly
          :rules="[{ required: true, message: '请选择相关信息' }]"
          @click="onclickEndTimePlan"
        />
        <van-cell-group v-if="taskSetting.autoTimeControl">
          <van-cell style="color:#646566" title="自动开始">
            <template #right-icon>
              <van-radio-group v-model="autoBegin" direction="horizontal">
                <van-radio name="0" icon-size="24px" style="font-size: 18px;">否</van-radio>
                <van-radio name="1" icon-size="24px" style="font-size: 18px;">是</van-radio>
              </van-radio-group>
            </template>
          </van-cell>
          <van-cell style="color:#646566" title="自动结束">
            <template #right-icon>
              <van-radio-group v-model="autoEnd" direction="horizontal">
                <van-radio name="0" icon-size="24px" style="font-size: 18px;">否</van-radio>
                <van-radio name="1" icon-size="24px" style="font-size: 18px;">是</van-radio>
              </van-radio-group>
            </template>
          </van-cell>
        </van-cell-group>
        <van-field v-if="taskSetting.autoTimeControl"
          v-model="aheadTimeNumber"
          label="提前开始"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="aheadTime=true"
        />
        <van-field v-if="taskSetting.autoTimeControl"
          v-model="delayTimeNumber"
          label="延后结束"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="delayTime=true"
        />
        <van-field
          v-if="taskSetting.setStation"
          v-model="stationName.text"
          label="所属车站"
          placeholder="请选择"
          input-align="right"
          readonly
          :rules="[{ required: true, message: '请选择相关信息' }]"
          @click="showStationList=true"
        />
        <van-field
          v-if="taskSetting.setOrg"
          v-model="orgName.text"
          label="所属组织"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="showOrgList=true"
        />
        <van-field v-model="taskInfo.workAreaComment" label="巡道地点" type="textarea" />
        <van-field v-model="taskInfo.workContent" label="巡道内容" type="textarea" />
        <van-field
          v-model="managerShow"
          :label="taskSetting.showInformation.managerShowName"
          input-align="right"
          readonly
          :rules="[{ required: true, message: '请选择相关信息' }]"
          @click="onclickRole('manager')"
        >
          <template #button>
            <van-button
              v-if="!manager.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('manager')"
            >本人</van-button>
            <van-button v-if="!manager.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="manager.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>

        <van-field
          v-if="taskInfo.state !== 5"
          v-model="petrolmanShow"
          label="巡道工"
          input-align="right"
          readonly
          :rules="[{ required: true, message: '请选择相关信息' }]"
          @click="onclickRole('petrolman')"
        >
          <template #button>
            <van-button
              v-if="!petrolman.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('petrolman')"
            >本人</van-button>
            <van-button v-if="!petrolman.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="petrolman.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          v-if="taskInfo.state !== 5"
          v-model="taskInfo.comment"
          type="textarea"
          autosize
          label="备注"
        />
        <van-popup v-model="showDateTimePicker" round position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            title="选择日期时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmDTP"
            @cancel="onCancelDTP"
          />
        </van-popup>
        <van-popup v-model="aheadTime" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="aheadTime = false"
            @confirm="onConfirmaheadTime"
          />
        </van-popup>
        <van-popup v-model="showStationList" round position="bottom">
          <van-cascader
            v-model="selecStation"
            title="请选择所属车站"
            :options="stationNameList"
            @close="showStationList = false"
            @finish="onConfirmStation"
          />
        </van-popup>
        <van-popup v-model="showOrgList" round position="bottom">
          <van-cascader
            v-model="selectOrg"
            title="请选择所属组织"
            :options="orgNameList"
            :field-names="orgProps"
            @close="showOrgList = false"
            @change="onConfirmOrg"
            @finish="onConfirmOrg2"
          />
          <van-button round type="info" style="width:120px;" @click="showOrgList = false">完成</van-button>
        </van-popup>
        <van-popup v-model="delayTime" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="delayTime = false"
            @confirm="onConfirmdelayTime"
          />
        </van-popup>
        <div class="submit-area">
          <van-button round style="width:120px;" @click="onCancelTaskCreate">取消</van-button>
          <van-button round type="info" style="width:120px;" @click="onSubmitTaskCreate">创建</van-button>
        </div>
      </van-form>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
import { getFormatDate, getFormatHourMinute, getFormatDateTime } from '@/utils/datetime'
import { mapGetters, createNamespacedHelpers } from 'vuex'
import { setOrgOptions } from '@/api/line_data'
import { getUserInfobyId, getDeviceInfobyId } from '../../api/userDeviceGroup'
import { convertUserInfoStruct, convertDeviceInfoStruct } from '../../utils/taskUtils'

const taskCreateStore = createNamespacedHelpers('taskCreate')
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      delayTimeNumber: '',
      aheadTimeNumber: '',
      stationName: '',
      orgName: {
        text: '',
        value: []
      },
      showStationList: false,
      showOrgList: false,
      stationNameList: [],
      orgNameList: [],
      orgProps: {
        value: 'orgId',
        text: 'orgName',
        children: 'children',
        checkStrictly: true
      },
      selecStation: '',
      selectOrg: '',
      columns: ['无', '五分钟', '十分钟', '十五分钟', '二十分钟', '二十五分钟', '三十分钟', '无'],
      aheadTime: false,
      delayTime: false,
      autoBegin: '0',
      autoEnd: '0',
      lineData: null,
      initTaskInfo: false,
      taskInfo: {
        beginTime_plan: 0,
        endTime_plan: 0,
        workAreaComment: '',
        workContent: '',
        comment: ''
      },
      show: {
        beginTime_plan: '',
        endTime_plan: '',
        workArea: '',
        fence: ''
      },
      showDateTimePicker: false,
      showWorkAreaPicker: false,
      curShow: '',
      minDate: new Date(2022, 1, 1),
      maxDate: new Date(2025, 12, 31),
      currentDate: new Date()
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'permission', 'myStationIds', 'taskSetting']),
    ...taskCreateStore.mapGetters(['showCreate', 'manager', 'petrolman', 'managerShow', 'petrolmanShow'])
  },
  watch: {},
  created() {
    if (this.$route.query.taskInfo && !this.initTaskInfo) {
      this.initTaskInfo = true
      this.taskInfo = this.$route.query.taskInfo
      this.show.beginTime_plan = this.getData(this.$route.query.taskInfo.beginTime_plan)
      this.show.endTime_plan = this.getData(this.$route.query.taskInfo.endTime_plan)
    }
  },
  mounted() {
    this.fillTaskCreateData()
    this.setTaskCreateData({ key: 'manager', value: this.$route.query.taskInfo.manager })
    this.setTaskCreateData({ key: 'petrolman', value: this.$route.query.taskInfo.petrolman })
  },
  methods: {
    ...taskCreateStore.mapMutations(['setShowCreate', 'setTaskCreateData']),
    getData(n) {
      const now = new Date(n)
      const y = now.getFullYear()
      const m = now.getMonth() + 1
      const d = now.getDate()
      const hour = now.getHours()
      const minute = now.getMinutes()
      return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute)
    },
    async onChooseMyDevice(role) {
      const deviceMsg = await getDeviceInfobyId(this.deviceId)
      if (deviceMsg.code === 0) {
        const members = []
        members.push(convertDeviceInfoStruct(deviceMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    async onChooseMyUser(role) {
      const userMsg = await getUserInfobyId(this.userId)
      if (userMsg.code === 0) {
        const members = []
        members.push(convertUserInfoStruct(userMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    jumpToMemberSelect(role, chosenItems) {
      this.setShowCreate(false)
      this.$router.push({ path: '/memberSelectXD', query: { role, chosenItems } })
    },
    async fillTaskCreateData() {
      this.stationNameList = this.myStationIds
      var res = await setOrgOptions()
      this.orgNameList.push(res)
      this.taskInfo.type = 3
      // this.fillShowData(this.taskInfo)
    },
    fillShowData(taskInfo) {
      // workArea Show
      // this.show.workArea = this.generateWorkareaShow()
    },
    onConfirmStation(value) {
      this.stationName = value.selectedOptions[0]
      this.showStationList = false
    },
    onConfirmOrg(value) {
      this.orgName.value = []
      this.orgName.text = value.selectedOptions.map((option) => option.orgName).join('/')
      this.orgName.value.push(value.selectedOptions.map((option) => option.orgId))
    },
    onConfirmOrg2(value) {
      this.orgName.value = []
      this.orgName.text = value.selectedOptions.map((option) => option.orgName).join('/')
      this.orgName.value.push(value.selectedOptions.map((option) => option.orgId))
      this.showOrgList = false
    },
    onclickBeginTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'beginTimePlanPicker'
    },
    onclickEndTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'endTimePlanPicker'
    },
    onclickRole(role) {
      this.jumpToMemberSelect(role, this[role])
    },
    onConfirmaheadTime(value) {
      this.aheadTimeNumber = value
      this.aheadTime = false
    },
    onConfirmdelayTime(value) {
      this.delayTimeNumber = value
      this.delayTime = false
    },
    onConfirmDTP(dateTime) {
      if (this.curShow === 'beginTimePlanPicker') {
        this.taskInfo.beginTime_plan = dateTime
        this.show.beginTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      } else if (this.curShow === 'endTimePlanPicker') {
        this.taskInfo.endTime_plan = dateTime
        this.show.endTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      }
      this.showDateTimePicker = false
    },
    onCancelDTP() {
      this.showDateTimePicker = false
    },
    async onSubmitTaskCreate() {
      if (this.taskInfo.beginTime_plan && this.taskInfo.endTime_plan && (!this.taskSetting.setStation || this.stationName.text) && (!this.taskSetting.setOrg || this.orgName.text) && this.managerShow && this.petrolmanShow) {
          // 表单校验通过，提交表单
        } else {
          // 表单校验未通过
          console.error('表单校验未通过')
          return false
        }
      const task = {
        type: 3,
        state: 3,
        taskName: this.taskInfo.taskName,
        autoBegin: parseInt(this.autoBegin),
        autoEnd: parseInt(this.autoEnd),
        beginTime_order: '',
        terminateTime_order: '',
        creater: { userId: this.userId, deviceInfo: { type: 'HT', id: this.deviceId } },
        beginTime_plan: this.show.beginTime_plan,
        endTime_plan: this.show.endTime_plan,
        manager: [],
        petrolman: [],
        workArea: {
          places: [],
          areaDescription: this.taskInfo.workAreaComment
        },
        workContent: this.taskInfo.workContent,
        comment: this.taskInfo.comment
      }
      if (this.stationName.value) {
        task.station = this.stationName.value
      }
      if (this.orgName.value) {
        task.org = this.orgName.value[0]
      }
      var aheadTimeList = { 无: 0, 五分钟: 1, 十分钟: 2, 十五分钟: 3, 二十分钟: 4, 二十五分钟: 5, 三十分钟: 6 }
      if (this.aheadTimeNumber) {
        task.beginTime_order = getFormatDateTime(new Date(this.taskInfo.beginTime_plan - aheadTimeList[this.aheadTimeNumber] * 60 * 5 * 1000))
      } else task.beginTime_order = task.beginTime_plan
      if (this.delayTimeNumber) {
        task.terminateTime_order = getFormatDateTime(new Date(this.taskInfo.endTime_plan + aheadTimeList[this.delayTimeNumber] * 60 * 5 * 1000))
      } else task.terminateTime_order = task.endTime_plan
      this.manager.forEach((item) => {
        task.manager.push({ type: item.type, id: item.id })
      })
      this.petrolman.forEach((item) => {
        task.petrolman.push({ type: item.type, id: item.id })
      })
      const { data } = await this.$http.post('/task/taskCreate', task)
      if (data.code === 0) {
        this.$toast('创建成功')
        this.$router.go(-1)
      } else {
        this.$toast(`创建失败${data.msg}`)
      }
    },
    onCancelTaskCreate() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.taskCreate {
  .workArea {
    .van-cell {
      font-size: 30px;
    }
    .van-form {
      .meter {
        /deep/.van-field__label {
          width: 90px;
        }
      }
      .kilo {
        /deep/.van-field__label {
          width: 192px;
        }
      }
    }
  }
  .submit-area {
    margin: 20px 100px;
    display: flex;
    justify-content: space-between;
  }
}
</style>
